package com.example.zbh.dsliao.ui.adapter;

import android.content.Context;
import android.support.v4.content.IntentCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.easemob.chat.EMConversation;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.db.DatabaseHelper;
import com.example.zbh.dsliao.db.entity.UserContact;
import com.example.zbh.dsliao.model.entity.ContactPeople;
import com.parse.ParseQuery;

import java.util.ArrayList;
import java.util.List;


/**
 * 通讯录列表适配器
 */
public class ContactAdapter extends BaseAdapter {
    private List<ContactPeople> list;
    private List<ContactPeople> copyList;
    private String userName;
    private boolean notiyfyByFilter;
    private MyFilter myFilter;
    private Context context;

    public ContactAdapter(Context context) {
        this.context = context;
    }

    public void addData(List<ContactPeople> list) {
        this.list = list;
        copyList = new ArrayList<ContactPeople>();
        copyList.addAll(list);
        notifyDataSetChanged();
    }

    private boolean islength() {
        return list != null && list.size() > 0;
    }

    @Override
    public int getCount() {
        return islength() ? list.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return list.get(position).getName();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contactlist_listview, null);

            holder = new ViewHolder();
            holder.tv_index = (TextView) convertView.findViewById(R.id.tv_index);
            holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            holder.userLayout = (LinearLayout) convertView.findViewById(R.id.userLayout);
            holder.header_avatar = (ImageView) convertView.findViewById(R.id.header_avatar);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        ContactPeople people = list.get(position);
        String currentLetter = people.getPinyin().charAt(0) + "";
        String indexStr = null;
        if (position == 0) {
            indexStr = currentLetter;
        } else {
            String preLetter = list.get(position - 1).getPinyin().charAt(0) + "";
            if (!TextUtils.equals(currentLetter, preLetter)) {
                indexStr = currentLetter;
            }
        }
        holder.tv_index.setVisibility(indexStr == null ? View.GONE : View.VISIBLE);
        holder.tv_index.setText(indexStr);
        holder.tv_name.setText(people.getName());
        UserContact userContact = DatabaseHelper.getInstance().queryContactPeopleBynickName(people.getName());
        if (userContact != null){
            String avatar = userContact.getAvatar();
            if (avatar != null){
                Glide.with(context).load(avatar)
                        .placeholder(R.drawable.dl_default_avatar)
                        .error(R.drawable.dl_default_avatar)
                        .into(holder.header_avatar);
            }
        }
        else{
            holder.header_avatar.setImageResource(R.drawable.dl_default_avatar);
        }


        holder.tv_name.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (onlongClickItemLisener != null) {
                    onlongClickItemLisener.onlongClickItem(v, 2, position);
                }
                return true;
            }
        });
        holder.tv_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onlongClickItemLisener != null) {
                    onlongClickItemLisener.onlongClickItem(v, 1, position);
                }
            }
        });

        userName = people.getName();

        return convertView;
    }


     class ViewHolder {
        private TextView tv_index, tv_name;
        private LinearLayout userLayout;
        private ImageView header_avatar;

        public ViewHolder getHolder(View view) {
            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.tv_index = (TextView) view.findViewById(R.id.tv_index);
                holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
                holder.userLayout = (LinearLayout) view.findViewById(R.id.userLayout);
                holder.header_avatar = (ImageView) view.findViewById(R.id.header_avatar);
            }
            return holder;
        }
    }


    private OnlongClickItemLisener onlongClickItemLisener;

    public void setOnlongClickItemLisener(OnlongClickItemLisener onlongClickItemLisener) {
        this.onlongClickItemLisener = onlongClickItemLisener;
    }

    public interface OnlongClickItemLisener {
        void onlongClickItem(View view, int code, int position);
    }


    public Filter getFilter() {
        if (myFilter == null) {
            myFilter = new MyFilter(list);
        }
        return myFilter;
    }


    /**
     * 搜索
     **/
    protected class MyFilter extends Filter {
        List<ContactPeople> mOriginalList = null;

        public MyFilter(List<ContactPeople> myList) {
            this.mOriginalList = myList;
        }

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();
            if (mOriginalList == null) {
                mOriginalList = new ArrayList<ContactPeople>();
            }

            if (prefix == null || prefix.length() == 0) {
                results.values = copyList;
                results.count = copyList.size();
            } else {
                String prefixString = prefix.toString();
                final int count = mOriginalList.size();
                final ArrayList<ContactPeople> newValues = new ArrayList<ContactPeople>();
                for (int i = 0; i < count; i++) {
                    final ContactPeople people = mOriginalList.get(i);
                    String username = people.getPinyin();
                    if (username == null) {
                        username = people.getPinyin();
                    }
                    if (username.startsWith(prefixString)) {
                        newValues.add(people);
                    } else {
                        final String[] words = username.split(" ");
                        final int wordCount = words.length;

                        // Start at index 0, in case valueText starts with space(s)
                        for (int k = 0; k < wordCount; k++) {
                            if (words[k].startsWith(prefixString)) {
                                newValues.add(people);
                                break;
                            }
                        }
                    }

                }
                results.values = newValues;
                results.count = newValues.size();
            }

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (list != null && list.size() > 0) {
                list.clear();
                list.addAll((List<ContactPeople>) results.values);
                if (results.count > 0) {
                    notiyfyByFilter = true;
                    notifyDataSetChanged();
                } else {
                    notifyDataSetChanged();
                }
            }


        }


    }


}
